﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;


public partial class upCommonFile : System.Web.UI.Page
{
    private  string _fileName=null;
    private CommFiles cf = new CommFiles();
    private ArrayList files=new ArrayList();
    private ArrayList sqlList=new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userName"] == null || Session["roleID"]==null)
        {
            Response.Redirect("~/Login.aspx");
            Response.End();
        }
            
        if(!IsPostBack)
            {
            BindFileInfo();
            }
        

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        lblMsg.Text = "";
        lblFailMsg.Text = "";

        string Dirpath = Server.MapPath("~\\files\\common\\");

        if (!Directory.Exists(Dirpath))
        {
            Directory.CreateDirectory(Dirpath);
        }


        for (int i = 0; i < Request.Files.Count;i++ )
        {
             string filePath= Request.Files[i].FileName;
             _fileName = filePath.Substring(filePath.LastIndexOf("\\")+1);
             //判断上传文件框里是否有文件
             if (_fileName!= "")
           {
               if (cf.FindFile(_fileName))
             {
                 lblFailMsg.Text = lblFailMsg.Text + "<font color='red'>存在同名文件：" + _fileName + "</font>;请更名后再上传该文件。<br/>";
             }
             else 
             {
                 //将文件名记录到动态数组，然后上传到服务器
                   if(!files.Contains(_fileName))
                   {
                     files.Add(_fileName);
                   }
                   try
                   {
                       Request.Files[0].SaveAs(Dirpath + _fileName);
                       //Request.Files[0].SaveAs(Server.MapPath("~/files/common/") + _fileName);
                   }
                   catch 
                   {
                       files.Remove(_fileName);
                   }
             }
           }
        }
      //循环数组，建立一个写入数据库的sql语句组
            for (int i = 0; i < files.Count; i++)
            {
                sqlList.Add("insert into commFiles(fileName) values('" + files[i] + "')");
            }
        if(files.Count>0)
        {
            if(cf.UploadFile(sqlList))
            {
                lblMsg.Text = "你已经成功上传了<font color='red'>"+files.Count+"</font>个文件！<br/>";
                BindFileInfo();
            }
       }
    }
             
 
   
    protected void BindFileInfo()
    {
        DataSet ds=cf.ReadFilesRecord();
        DataView dv = ds.Tables["commFiles"].DefaultView;
        dv.Sort="fileID asc";
        dgCommFiles.DataSource =dv ;
        dgCommFiles.DataBind();

    }

    /// <summary>
    /// 删除事件
    /// </summary>
    /// <param name="source"></param>
    /// <param name="e"></param>
    protected void dgCommFiles_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        int fileID = 0;
        string fileName = null;
        ArrayList sqlList = new ArrayList();
        ArrayList fileList = new ArrayList();
        switch (e.CommandName)
        {
                
            case "delete":
                 fileID =Convert.ToInt32( e.Item.Cells[0].Text);
                 fileName = e.Item.Cells[2].Text;
                 if (cf.DelectFile(fileID))
                 {

                     DelFile(fileName);
                     Response.Write("<script language='javascript'>alert('删除成功！')</script>");
                     BindFileInfo();
                 }
                 else 
                 {
                     Response.Write("<script language='javascript'>alert('在尝试对数据库进行操作时，发送未知意外，删除失败！请联系管理员。')</script>");
                 }
                break;
            case "delAll":
                foreach(DataGridItem dg in dgCommFiles.Items)
                {
                    CheckBox chk = (CheckBox)dg.FindControl("chkSingle");
                    if(chk.Checked)
                    {
                    fileID =Convert.ToInt32( dg.Cells[0].Text);
                    fileName = dg.Cells[2].Text;
                    sqlList.Add("delete from commFiles where fileID="+fileID);
                    fileList.Add(fileName);
                    }
                }
                if(cf.DeleteAll(sqlList))
                {
                    for (int i = 0; i < fileList.Count;i++ )
                    {
                        DelFile(Convert.ToString( fileList[i]));
                     
                    }
                    Response.Write("<script language='javascript'>alert('删除成功！')</script>");
                    BindFileInfo();
                }
                else
                {
                    Response.Write("<script language='javascript'>alert('在尝试对数据库进行操作时，发送未知意外，删除失败！请联系管理员。')</script>");
                }
                break;

        }
    }
    /// <summary>
    /// 删除硬盘上的文件
    /// </summary>
    /// <param name="fileName"></param>
    protected void DelFile(string fileName)
    {
        FileInfo fi = new FileInfo(Server.MapPath("~/files/common/") + fileName);
        fi.Delete();
    }
    /// <summary>
    /// 全选
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void chkAll_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkAll = (CheckBox)sender;
        foreach(DataGridItem dg in dgCommFiles.Items)
        {
            CheckBox chk = (CheckBox)dg.FindControl("chkSingle");
            chk.Checked = chkAll.Checked;
        }
    }
    protected void dgCommFiles_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
        dgCommFiles.CurrentPageIndex = e.NewPageIndex;
        BindFileInfo();
    }
}
